package com.hhq.system.plugin.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hhq.system.security.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatis-plus 字段自动填充
 *
 * @author haoxr
 * @since 2022/10/14
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增填充创建时间
     *
     * @param metaObject 元数据
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean hasCreateTime = metaObject.hasSetter("createTime") && metaObject.hasGetter("createTime");
        if (hasCreateTime) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        }
        boolean hasUpdateTime = metaObject.hasSetter("updateTime") && metaObject.hasGetter("updateTime");
        if (hasUpdateTime) {
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        }

        if (null != SecurityUtils.getUser()) {
            boolean hasCreateBy = metaObject.hasSetter("createBy") && metaObject.hasGetter("createBy");
            if (hasCreateBy) {
                this.strictInsertFill(metaObject, "createBy", () -> SecurityUtils.getUser().getUserId(), Long.class);
            }
            boolean hasTenantId = metaObject.hasSetter("tenantId") && metaObject.hasGetter("tenantId");
            if (hasTenantId) {
                this.strictUpdateFill(metaObject, "tenantId", () -> SecurityUtils.getUser().getTenantId(), String.class);
            }
        }
    }

    /**
     * 更新填充更新时间
     *
     * @param metaObject 元数据
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        if (null != SecurityUtils.getUser()) {
            boolean hasUpdateBy = metaObject.hasSetter("updateBy") && metaObject.hasGetter("updateBy");
            if (hasUpdateBy) {
                this.strictInsertFill(metaObject, "updateBy", () -> SecurityUtils.getUser().getUserId(), Long.class);
            }
            boolean hasTenantId = metaObject.hasSetter("tenantId") && metaObject.hasGetter("tenantId");
            if (hasTenantId) {
                this.strictUpdateFill(metaObject, "tenantId", () -> SecurityUtils.getUser().getTenantId(), String.class);
            }
        }
    }

}
